package room

import (
	"context"
	"sync"

	"gitee.com/lichenxin/grpc-consul-server/pkg/consul"
	"gitee.com/lichenxin/grpc-consul-server/pkg/pb"
	"gitee.com/lichenxin/grpc-consul-server/pkg/utils"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

// ServerName 服务名称
const ServerName = "CustomRoomServer"

var (
	roomServer     *Server
	roomServerOnce sync.Once
)

// Server 服务端
type Server struct {
	pb.UnimplementedRoomServer
	mutex    sync.Mutex
	serverID string
	l        *logrus.Entry
}

// GetServer 获取服务端
func GetServer() *Server {
	roomServerOnce.Do(func() {
		roomServer = &Server{
			l: logrus.WithField("channel", "server"),
		}
	})
	return roomServer
}

// Register 注册
func (s *Server) Register(port int) error {
	serverID, err := consul.AddServer(ServerName, port)
	if err != nil {
		return errors.WithStack(err)
	}
	s.serverID = serverID
	s.l.WithField("serverID", s.serverID).Info("register server")
	return nil
}

// Stop 停止
func (s *Server) Stop() {
	s.l.WithField("serverID", s.serverID).Info("stop server")
	if s.serverID != "" {
		_ = consul.DelServer(s.serverID)
	}
}

var memberCount int64

// Join 加入
func (s *Server) Join(ctx context.Context, req *pb.JoinRoomRequest) (*pb.JoinRoomResponse, error) {
	s.l.WithField("userID", req.UserID).Info("join room")

	memberCount++

	roomID := utils.RandInt(1000, 9999)
	return &pb.JoinRoomResponse{
		RoomID:      int64(roomID),
		UserID:      req.UserID,
		MemberCount: memberCount,
	}, nil
}
